<template>
  <el-dialog
    v-model="dialogVisible"
    title="创建新实例"
    width="50%"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    class="instance-add-dialog"
  >
    <div class="instance-add-content">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        class="instance-form"
      >
        <el-form-item label="实例名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入实例名称" />
        </el-form-item>
        <el-form-item label="UE工程" prop="projectId">
          <el-select
            v-model="formData.projectId"
            placeholder="请选择UE工程"
            class="w-full"
          >
            <el-option
              v-for="project in projects"
              :key="project._id"
              :label="project.originalName"
              :value="project._id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="GPU选择" prop="gpuId">
          <div class="gpu-cards" v-loading="loading">
            <div
              v-for="gpu in gpuList"
              :key="gpu.id"
              class="gpu-card"
              :class="{ 'gpu-card-selected': formData.gpuId === gpu.id }"
              @click="formData.gpuId = gpu.id"
            >
              <div class="gpu-info">
                <div class="gpu-header">
                  <span class="gpu-index">GPU-{{ gpu.index }}</span>
                  <span class="gpu-load">负载率: {{ gpu.load }}%</span>
                </div>
                <div class="gpu-model">{{ gpu.model }}</div>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="使用默认分辨率">
          <el-switch v-model="formData.useDefaultResolution" />
        </el-form-item>

        <template v-if="!formData.useDefaultResolution">
          <el-form-item label="宽度" prop="width">
            <el-input-number
              v-model="formData.resolutionX"
              :min="1"
              :max="7680"
              :step="1"
              placeholder="请输入宽度"
            />
          </el-form-item>

          <el-form-item label="高度" prop="height">
            <el-input-number
              v-model="formData.resolutionY"
              :min="1"
              :max="4320"
              :step="1"
              placeholder="请输入高度"
            />
          </el-form-item>
        </template>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">创建</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from "vue";
import { ElMessage } from "element-plus";
import { getGpuInfo } from "@/api/modules/system.js";
import { createInstance } from "@/api/modules/ueInstance.js";
import { getUeProjects } from "@/api/modules/ueProject.js";
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:visible",'refresh']);

// 控制对话框显示
const dialogVisible = ref(props.visible);

// 监听dialogVisible的变化
watch(
  () => dialogVisible.value,
  (newVal) => {
    emit("update:visible", newVal);
  }
);

// 监听props.visible的变化
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal;
    if (newVal) {
      fetchGpuInfo();
      fetchUeProjects();
    }
  }
);

// 表单引用
const formRef = ref(null);

// 表单数据
const formData = ref({
  name: "",
  gpuId: "",
  projectId: "",
  useDefaultResolution: true,
  resolutionX: 1920,
  resolutionY: 1080,
});

// GPU数据
const gpuList = ref([]);
const loading = ref(false);

// 获取GPU信息
const fetchGpuInfo = async () => {
  loading.value = true;
  try {
    const { data } = await getGpuInfo();
    gpuList.value = data.map((gpu, index) => ({
      id: index,
      index,
      model: gpu.model,
      load: Math.round((gpu.used / gpu.total) * 100),
    }));
    // 找出负载最低的GPU并自动选择
    const minLoadGpu = gpuList.value.reduce(
      (min, gpu) => (gpu.load < min.load ? gpu : min),
      gpuList.value[0]
    );
    formData.value.gpuId = minLoadGpu.id;
  } catch (error) {
    console.error("获取GPU信息失败:", error);
    ElMessage.error("获取GPU信息失败");
  } finally {
    loading.value = false;
  }
};

// 模拟UE工程数据
const projects = ref([]);
const fetchUeProjects = async () => {
  try {
    const { data } = await getUeProjects();
    projects.value = data.filter(item => item.extractStatus == 'completed');
  } catch (error) {
    console.error("获取UE工程信息失败:", error);
    ElMessage.error("获取UE工程信息失败");
  }
};
// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入实例名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  gpuId: [{ required: true, message: "请选择GPU", trigger: "change" }],
  projectId: [{ required: true, message: "请选择UE工程", trigger: "change" }],
  resolutionX: [
    { required: true, message: "请输入宽度", trigger: "blur" },
    { type: "number", message: "宽度必须为数字", trigger: "blur" },
  ],
  resolutionY: [
    { required: true, message: "请输入高度", trigger: "blur" },
    { type: "number", message: "高度必须为数字", trigger: "blur" },
  ],
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    // TODO: 调用创建实例的API
    console.log("提交的表单数据:", formData.value);
    createInstance(formData.value)
      .then(() => {
        ElMessage.success("已提交创建申请");
        emit('refresh');
      })
      .catch((err) => {
        console.log(err);
        ElMessage.error(err.response.data.error);
      });
    dialogVisible.value = false;
  } catch (error) {
    // 表单验证失败
    console.error("表单验证失败:", error);
  }
};
</script>

<style scoped>
.instance-add-dialog {
  .instance-add-content {
    padding: 20px;
  }

  .instance-form {
    max-width: 600px;
    margin: 0 auto;

    .gpu-cards {
      display: flex;
      gap: 16px;
      flex-wrap: wrap;

      .gpu-card {
        flex: 1;
        min-width: 200px;
        padding: 16px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          border-color: #409eff;
          transform: translateY(-2px);
        }

        &.gpu-card-selected {
          border-color: #409eff;
          background-color: #ecf5ff;
        }

        .gpu-info {
          .gpu-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;

            .gpu-index {
              font-weight: bold;
              color: #303133;
            }

            .gpu-load {
              color: #67c23a;
            }
          }

          .gpu-model {
            color: #606266;
            font-size: 14px;
          }
        }
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 20px;
  }

  :deep(.el-input-number) {
    width: 100%;
  }

  .w-full {
    width: 100%;
  }
}
</style>
